package thread;

import java.util.concurrent.*;
import java.util.List;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * Java 线程池示例大全
 * 展示 Java 中各种线程池的使用方法和场景
 */
public class ThreadPoolExamples {

    /**
     * 1. FixedThreadPool 固定大小线程池示例
     */
    public static void fixedThreadPoolExample() {
        System.out.println("=== FixedThreadPool 示例 ===");
        
        // 创建固定大小为3的线程池
        ExecutorService fixedPool = Executors.newFixedThreadPool(3);
        
        // 提交10个任务
        for (int i = 1; i <= 10; i++) {
            final int taskId = i;
            fixedPool.execute(() -> {
                System.out.println("任务 " + taskId + " 由线程 " + Thread.currentThread().getName() + " 执行");
                try {
                    Thread.sleep(1000); // 模拟任务执行
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }
        
        fixedPool.shutdown();
        try {
            fixedPool.awaitTermination(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    /**
     * 2. CachedThreadPool 缓存线程池示例
     */
    public static void cachedThreadPoolExample() {
        System.out.println("\n=== CachedThreadPool 示例 ===");
        
        // 创建可缓存的线程池
        ExecutorService cachedPool = Executors.newCachedThreadPool();
        
        // 提交大量短时间任务
        for (int i = 1; i <= 20; i++) {
            final int taskId = i;
            cachedPool.execute(() -> {
                System.out.println("任务 " + taskId + " 由线程 " + Thread.currentThread().getName() + " 执行");
                try {
                    Thread.sleep(500); // 短任务
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }
        
        cachedPool.shutdown();
        try {
            cachedPool.awaitTermination(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    /**
     * 3. SingleThreadExecutor 单线程线程池示例
     */
    public static void singleThreadExecutorExample() {
        System.out.println("\n=== SingleThreadExecutor 示例 ===");
        
        // 创建单线程线程池
        ExecutorService singlePool = Executors.newSingleThreadExecutor();
        
        // 提交5个任务，保证按顺序执行
        for (int i = 1; i <= 5; i++) {
            final int taskId = i;
            singlePool.execute(() -> {
                System.out.println("任务 " + taskId + " 由线程 " + Thread.currentThread().getName() + " 执行");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }
        
        singlePool.shutdown();
        try {
            singlePool.awaitTermination(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    /**
     * 4. ScheduledThreadPool 定时任务线程池示例
     */
    public static void scheduledThreadPoolExample() {
        System.out.println("\n=== ScheduledThreadPool 示例 ===");
        
        // 创建调度线程池
        ScheduledExecutorService scheduledPool = Executors.newScheduledThreadPool(3);
        
        // 延迟3秒后执行一次
        scheduledPool.schedule(() -> {
            System.out.println("延迟任务执行 - " + System.currentTimeMillis());
        }, 3, TimeUnit.SECONDS);
        
        // 初始延迟1秒，然后每2秒执行一次
        scheduledPool.scheduleAtFixedRate(() -> {
            System.out.println("周期性任务执行 - " + System.currentTimeMillis());
        }, 1, 2, TimeUnit.SECONDS);
        
        // 运行5秒后关闭
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        
        scheduledPool.shutdown();
    }

    /**
     * 5. WorkStealingPool 工作窃取线程池示例（Java 8+）
     */
    public static void workStealingPoolExample() {
        System.out.println("\n=== WorkStealingPool 示例 ===");
        
        // 创建工作窃取线程池
        ExecutorService workStealingPool = Executors.newWorkStealingPool();
        
        // 提交大量递归任务
        List<Callable<String>> tasks = new ArrayList<>();
        for (int i = 1; i <= 10; i++) {
            final int taskId = i;
            tasks.add(() -> {
                System.out.println("工作窃取任务 " + taskId + " 由线程 " + Thread.currentThread().getName() + " 执行");
                Thread.sleep(1000);
                return "任务 " + taskId + " 完成";
            });
        }
        
        try {
            workStealingPool.invokeAll(tasks);
            workStealingPool.shutdown();
            workStealingPool.awaitTermination(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    /**
     * 6. 自定义线程工厂示例
     */
    public static void customThreadFactoryExample() {
        System.out.println("\n=== 自定义线程工厂示例 ===");
        
        // 创建自定义线程工厂
        ThreadFactory customFactory = new ThreadFactory() {
            private final AtomicInteger threadNumber = new AtomicInteger(1);
            private final String namePrefix = "CustomThread-";
            
            @Override
            public Thread newThread(Runnable r) {
                Thread t = new Thread(r, namePrefix + threadNumber.getAndIncrement());
                t.setDaemon(false);
                t.setPriority(Thread.NORM_PRIORITY);
                return t;
            }
        };
        
        // 使用自定义工厂创建线程池
        ExecutorService customPool = Executors.newFixedThreadPool(3, customFactory);
        
        for (int i = 1; i <= 5; i++) {
            final int taskId = i;
            customPool.execute(() -> {
                System.out.println("任务 " + taskId + " 由自定义线程 " + Thread.currentThread().getName() + " 执行");
            });
        }
        
        customPool.shutdown();
        try {
            customPool.awaitTermination(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    /**
     * 7. 线程池参数调优示例
     */
    public static void customThreadPoolExample() {
        System.out.println("\n=== 自定义线程池参数示例 ===");
        
        // 手动创建线程池，自定义所有参数
        ThreadPoolExecutor customPool = new ThreadPoolExecutor(
            2,                      // 核心线程数
            4,                      // 最大线程数
            60,                     // 空闲线程存活时间
            TimeUnit.SECONDS,       // 时间单位
            new LinkedBlockingQueue<>(10), // 任务队列
            new ThreadFactory() {
                private final AtomicInteger threadNumber = new AtomicInteger(1);
                @Override
                public Thread newThread(Runnable r) {
                    return new Thread(r, "CustomPool-Thread-" + threadNumber.getAndIncrement());
                }
            },
            new ThreadPoolExecutor.AbortPolicy() // 拒绝策略
        );
        
        // 提交任务
        for (int i = 1; i <= 10; i++) {
            final int taskId = i;
            try {
                customPool.execute(() -> {
                    System.out.println("自定义线程池任务 " + taskId + " 由线程 " + Thread.currentThread().getName() + " 执行");
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                });
            } catch (Exception e) {
                System.out.println("任务 " + taskId + " 被拒绝: " + e.getMessage());
            }
        }
        
        customPool.shutdown();
        try {
            customPool.awaitTermination(20, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    /**
     * 8. 线程池监控示例
     */
    public static void threadPoolMonitoringExample() {
        System.out.println("\n=== 线程池监控示例 ===");
        
        ThreadPoolExecutor monitoredPool = new ThreadPoolExecutor(
            2, 4, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(5)
        );
        
        // 提交任务
        for (int i = 1; i <= 10; i++) {
            final int taskId = i;
            monitoredPool.execute(() -> {
                System.out.println("监控任务 " + taskId + " 执行中...");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }
        
        // 监控线程池状态
        while (!monitoredPool.isTerminated()) {
            System.out.printf("活跃线程数: %d, 队列任务数: %d, 完成任务数: %d%n",
                monitoredPool.getActiveCount(),
                monitoredPool.getQueue().size(),
                monitoredPool.getCompletedTaskCount());
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                break;
            }
        }
        
        monitoredPool.shutdown();
    }

    /**
     * 9. CompletableFuture 与线程池结合示例
     */
    public static void completableFutureWithThreadPoolExample() {
        System.out.println("\n=== CompletableFuture 与线程池结合示例 ===");
        
        ExecutorService executor = Executors.newFixedThreadPool(3);
        
        // 使用线程池执行异步任务
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("异步任务1 在 " + Thread.currentThread().getName() + " 执行");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            return "结果1";
        }, executor);
        
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("异步任务2 在 " + Thread.currentThread().getName() + " 执行");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            return "结果2";
        }, executor);
        
        // 组合两个异步任务的结果
        CompletableFuture<String> combined = future1.thenCombine(future2, (result1, result2) -> {
            return result1 + " + " + result2;
        });
        
        try {
            System.out.println("组合结果: " + combined.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        executor.shutdown();
    }

    /**
     * 10. ForkJoinPool 示例
     */
    public static void forkJoinPoolExample() {
        System.out.println("\n=== ForkJoinPool 示例 ===");
        
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        
        // 创建递归任务
        SumTask task = new SumTask(1, 10000);
        long result = forkJoinPool.invoke(task);
        System.out.println("1到10000的和: " + result);
        
        forkJoinPool.shutdown();
    }
    
    /**
     * 递归求和任务
     */
    static class SumTask extends RecursiveTask<Long> {
        private final long start;
        private final long end;
        private static final long THRESHOLD = 1000;
        
        SumTask(long start, long end) {
            this.start = start;
            this.end = end;
        }
        
        @Override
        protected Long compute() {
            if (end - start <= THRESHOLD) {
                // 小任务直接计算
                long sum = 0;
                for (long i = start; i <= end; i++) {
                    sum += i;
                }
                return sum;
            } else {
                // 大任务拆分
                long mid = start + (end - start) / 2;
                SumTask leftTask = new SumTask(start, mid);
                SumTask rightTask = new SumTask(mid + 1, end);
                
                leftTask.fork();
                rightTask.fork();
                
                return leftTask.join() + rightTask.join();
            }
        }
    }

    public static void main(String[] args) {
        System.out.println("Java 线程池示例大全");
        System.out.println("=".repeat(50));
        
        // 依次运行所有示例
        fixedThreadPoolExample();
        cachedThreadPoolExample();
        singleThreadExecutorExample();
        scheduledThreadPoolExample();
        workStealingPoolExample();
        customThreadFactoryExample();
        customThreadPoolExample();
        threadPoolMonitoringExample();
        completableFutureWithThreadPoolExample();
        forkJoinPoolExample();
        
        System.out.println("\n所有线程池示例执行完成！");
    }
}